package sit.engreal.leetcode.problems100;

import org.junit.jupiter.api.Assertions;

/**
 * <a href="https://leetcode.cn/problems/longest-common-prefix/"> 14. 最长公共前缀 </a>
 */
public class LeetCode14 {
    static class Solution {
        public String longestCommonPrefix(String[] strs) {
            final StringBuilder prefix = new StringBuilder();

            for (int i = 0; ; i++) {
                if (i >= strs[0].length()) {
                    return prefix.toString();
                }
                final char c = strs[0].charAt(i);
                for (int j = 1; j < strs.length; j++) {
                    if (i >= strs[j].length()) {
                        return prefix.toString();
                    }
                    if (c != strs[j].charAt(i)) {
                        return prefix.toString();
                    }
                }
                prefix.append(c);
            }
        }
    }

    public static void main(String[] args) {
        final Solution solution = new Solution();

        Assertions.assertEquals("fl",
                solution.longestCommonPrefix(new String[]{"flower", "flow", "flight"}));
        Assertions.assertEquals("",
                solution.longestCommonPrefix(new String[]{"dog", "racecar", "car"}));
        Assertions.assertEquals("a",
                solution.longestCommonPrefix(new String[]{"a"}));
    }
}
